<?php
class mxwSetup
{
    /**
     * setup
     * 
     * If the tablesExist function returns false, this
     * function creates the tables in the MODx database
     * 
     * @return void
     * @author Scotty Delicious
     */
    public static function setup()
    {
        if (!self::tablesExist()) self::createTables();
    }
    
    /**
     * tablesExist
     *
     * Check for the existence of MXW Product table.
     * Retunrs true if table exits and false if it does not.
     *
     * @return <boolean>
     * @author Scotty Delicious
     */
    public static function tablesExist()
    {
        global $modx;
        $tableExists = FALSE;
        include(MODX_BASE_PATH.'manager/includes/config.inc.php');
        $sql = "SHOW TABLES LIKE '".$table_prefix."mxw_products'";
        $query = $modx->db->query($sql);
        if (mysql_num_rows ($query) > 0) $tableExists = TRUE;
        return $tableExists;
    }
    
    /**
     * createTables
     *
     * Inserts the MODx Warehouse tables into the database.
     *
     * @return void
     * @author Scotty Delicious
     */
    public static function createTables()
    {
        global $modx;
        include(MODX_BASE_PATH.'manager/includes/config.inc.php');
        $tables = file_get_contents(MXW_BASE.'tables.sql');
        $tables = str_replace('MODXPREFIX_', $table_prefix, $tables);
        $tables = explode('--', $tables);
        
        foreach ($tables as $sql)
        {
            $query = $modx->db->query($sql);
        }
    }
    
    /**
     * getLexicon
     *
     * returns an object containing the files to include
     * for the manager and MXW lexicon.
     *
     * @return <object> $lexicon
     * @author Scotty Delicious
     */
    public static function getLexicon()
    {
        global $modx;
        $manager_language = '';
        $lexicon = new stdClass;
        
        // If this is an AJAX post and the DocumentParser was 
        // not executed, get the manager_language manually.
        if (!$modx->config['manager_language'])
        {
            $config_table = $modx->getFullTableName('system_settings');
            $sql = "SELECT `setting_value` FROM $config_table WHERE `setting_name`='manager_language'";
            $query = $modx->db->query($sql);
            $row = $modx->db->getRow($query);
            $manager_language = $row['setting_value'];
        }
        
        // Otherwise, get it the simple way.
        else
        {
            $manager_language = $modx->config['manager_language'];
        }
        
        $lexicon->manager = MODX_BASE_PATH.'manager/includes/lang/' . $manager_language. '.inc.php';
        if ( file_exists(MXW_BASE.'lexicon/'.$manager_language.'.inc.php') )
        {
            $lexicon->mxw = MXW_BASE.'lexicon/'.$manager_language.'.inc.php';
        }
        else
        {
            $lexicon->mxw = MXW_BASE.'lexicon/english.inc.php';
        }
        
        return $lexicon;
    }
}